# coding:utf-8

import requests
from TestCase.receivingLogistics import ReceivingLogistics
import re, time, os
from Common.Config import Config

step_wuliu = Config().get_conf('comm', 'step_wuliu')

R = ReceivingLogistics()
R.expressNum()
if step_wuliu == '1':
    os._exit(0)
R.unpackage()
if step_wuliu == '2':
    os._exit(0)
R.logistics()
if step_wuliu == '3':
    os._exit(0)
R.receiveProduct()
if step_wuliu == '4':
    os._exit(0)


class InspectionOperation():
    def __init__(self):
        self.session = requests.session()

    # 获取物品信息，因为测试环境不稳定，如果没有获取到物品信息，循环调用次接口，最多20次
    def getInspectionProduct(self):
        GetInspectionProductUrl = 'http://uat.ocs.aihuishou.com/InspectionOperation/GetInspectionProduct?productNo=' + str(
            R.orderNum)
        # print(GetInspectionProductUrl)
        count = 0
        while count <= 10:
            GetInspectionProductRequest = self.session.get(url=GetInspectionProductUrl, cookies=R.cookie, timeout=10)
            GetInspectionProductRequestError = GetInspectionProductRequest.json()['error']
            print("-->获取物品信息接口请求结果：", GetInspectionProductRequest.content.decode('utf8'))
            if GetInspectionProductRequestError == 0:
                GetInspectionProductRequestData = GetInspectionProductRequest.json()['data']
                print("获取物品质检信息数据：", GetInspectionProductRequestData)
                return GetInspectionProductRequestData
            time.sleep(10)
            count += 1

    # 质检
    def InspectionProduct(self):
        data = self.getInspectionProduct()
        # 提取物品信息
        productNo = data['productNo']
        inspectionType = data['inspectionType']
        inspectionStandard = data['inspectionStandard']
        productId = data['productId']
        originalPriceUnitss = data['originalPriceUnits']
        print(originalPriceUnitss)
        print(type(originalPriceUnitss))
        SubmitStepInspectionResultUrl = 'http://uat.ocs.aihuishou.com/InspectionOperation/SubmitStepInspectionResult'
        RecalculateProductPriceUrl = 'http://uat.ocs.aihuishou.com/InspectionOperation/RecalculateProductPrice?productNo=' + str(
            productNo) + '&newPriceValueUnit=' + str(
            originalPriceUnitss.strip(';')) + '&productId=' + str(productId)
        print(RecalculateProductPriceUrl)
        RecalculateProductPriceData = {
            "productNo": productNo,
            "newPriceValueUnit": originalPriceUnitss,
            "productId": productId
        }
        print(RecalculateProductPriceData)

        RecalculateProductPriceResult = self.session.get(RecalculateProductPriceUrl,
                                                         data=RecalculateProductPriceData, cookies=R.cookie)
        print(RecalculateProductPriceResult.text)
        RecalculateProductPriceResultError = RecalculateProductPriceResult.json()['error']
        if RecalculateProductPriceResultError == 0:
            newPrice = RecalculateProductPriceResult.json()['data']['newPrice']
            skuId = RecalculateProductPriceResult.json()['data']['skuId']
            skuName = RecalculateProductPriceResult.json()['data']['skuName']
            # inquiryKey = RecalculateProductPriceResult.json()['data']['inquiryKey']
            deduction = RecalculateProductPriceResult.json()['data']['deduction']
            exemption = RecalculateProductPriceResult.json()['data']['exemption']
            levelId = RecalculateProductPriceResult.json()['data']['levelId']
            levelName = RecalculateProductPriceResult.json()['data']['levelName']
            inspectionPropertyModels = []
            SubmitStepInspectionResultData = {
                "productNo": productNo,
                "productId": productId,
                "inspectionType": inspectionType,
                "inspectionStandard": inspectionStandard,
                "inspectionStep": 1,
                "imei": 'Auto_' + str(int(time.time())),
                "inspectionRemark": '',
                "imeiNegligibleReason": '无法显示',
                "inspectionFlags": 0,
                "appInspectionCode": '',
                "isFinalStep": True,
                "EraseStatus": 1,
                "newPrice": newPrice,
                "inquiryKey": "",
                "productSkuId": skuId,
                "productSkuName": skuName,
                "productLevelId": levelId,
                "productLevelName": levelName,
                "exemption": exemption,
                "attachLabelFlag": 0,
            }

            dataId = re.findall('\d+', originalPriceUnitss)
            print(dataId)
            for i in dataId:
                inspectionPropertyModels.append(i)
                # print(inspectionPropertyModels)
            for j in range(len(inspectionPropertyModels)):
                SubmitStepInspectionResultData.update({"inspectionPropertyModels[%s].step" % j: 1})
                SubmitStepInspectionResultData.update(
                    {"inspectionPropertyModels[%s].propertyType" % j: 1})
                SubmitStepInspectionResultData.update(
                    {"inspectionPropertyModels[%s].oldPropertyValueId" % j: inspectionPropertyModels[
                        j]})
                SubmitStepInspectionResultData.update(
                    {"inspectionPropertyModels[%s].newPropertyValueId" % j: inspectionPropertyModels[
                        j]})
                SubmitStepInspectionResultData.update(
                    {"inspectionPropertyModels[%s].detailRemark" % j: ''})
                SubmitStepInspectionResultData.update(
                    {"inspectionPropertyModels[%s].operatorId" % j: 2609})  # 质检员的ID的，2609是我（殷燕）的
                SubmitStepInspectionResultData.update(
                    {"inspectionPropertyModels[%s].autoDetected" % j: False})
                SubmitStepInspectionResultData.update(
                    {"inspectionPropertyModels[%s].authentication" % j: 0})
                # inspectionDate.update({"" % j: 'undefined'})
                # inspectionDate.update({"" % j: None})
            print(SubmitStepInspectionResultData)
            SubmitStepInspectionResult = self.session.post(url=SubmitStepInspectionResultUrl,
                                                           data=SubmitStepInspectionResultData, cookies=R.cookie)
            print(SubmitStepInspectionResult.json())
        else:
            print("提交结果按钮有问题")

    # 理货操作
    def scanAndBind(self):
        # 先检查需要添加的中转箱类型
        GetTransferDetailUrl = 'http://uat.ocs.aihuishou.com/Tally/GetTransferDetail?productNo=' + str(R.orderNum)
        GetTransferDetailRequest = self.session.get(url=GetTransferDetailUrl, cookies=R.cookie)
        print("检查中转箱类型请求URL:", GetTransferDetailUrl)
        print("检查中转箱类型请求结果：", GetTransferDetailRequest.text)
        GetTransferDetailRequestError = GetTransferDetailRequest.json()['error']
        if GetTransferDetailRequestError == 0:
            productFlow = GetTransferDetailRequest.json()['data']['productFlow']
            print("中转箱类型ID：", productFlow)
        else:
            print("获取中转箱信息失败")
        # 添加相应的中转箱
        ScanAndBindUrl = 'http://uat.ocs.aihuishou.com/RelayBox/ScanAndBind'
        ScanAndBindData = {
            "RelayBoxNo": R.relayBoxNo,
            "flow": productFlow
        }
        ScanAndBindReuqest = self.session.post(url=ScanAndBindUrl, data=ScanAndBindData, cookies=R.cookie)
        ScanAndBindReuqestError = ScanAndBindReuqest.json()['error']
        if ScanAndBindReuqestError == 0:
            addProductRequest = self.session.get(url=GetTransferDetailUrl, cookies=R.cookie)
            addProductRequestError = addProductRequest.json()['error']
            bindProductRelayBoxUrl = 'http://uat.ocs.aihuishou.com/RelayBox/BindProductRelayBox'
            bindProductRelayBoxData = {
                "ProductNo": str(R.orderNum),
                "ProductFlow": productFlow,
                "RelayBoxNo": R.relayBoxNo
            }
            bindProductRelayBoxReq = self.session.post(url=bindProductRelayBoxUrl, data=bindProductRelayBoxData,
                                                       cookies=R.cookie)
            bindProductRelayBoxReqError = bindProductRelayBoxReq.json()['error']

            if addProductRequestError == 0 and bindProductRelayBoxReqError == 0:
                TransferUrl = 'http://uat.ocs.aihuishou.com/RelayBox/Transfer'  # 移交
                TransferData = {
                    "RelayBoxNo": R.relayBoxNo
                }
                TransferRequest = self.session.post(url=TransferUrl, data=TransferData, cookies=R.cookie)
                TransferRequestError = TransferRequest.json()['error']
                print("IPQC移交结果：", TransferRequest.text)
                if TransferRequestError == 0:
                    print("IPQC物品移交成功")
                else:
                    print("IPQC物品移交失败")
            else:
                print("添加物品失败")
        else:
            print("添加中转箱失败")

    # CRM支付
    def orderpay(self):
        print('crm支付等后续把质检差异的脚本写好后再补上')

    # 理货查询，判断物品的流向，如果是IPQC的话，继续质检
    def tally(self):
        time.sleep(30)
        tallyUrl = 'http://uat.ocs.aihuishou.com/Tally/Search'
        tallyData = {
            "TransferProductNos": R.orderNum,
            "pageSize": 20
        }
        tallyRequest = self.session.post(url=tallyUrl, data=tallyData, cookies=R.cookie)
        print(tallyRequest.text)

        if tallyRequest.json()['error'] == 0:
            tallyRequestTransferDept = tallyRequest.json()['data']['items'][0]['transferDept']  # 移交部门
            print("理货查询物品状态：", tallyRequestTransferDept)

            tallyRequestReceiveDept = tallyRequest.json()['data']['items'][0]['receiveDept']  # 接收部门
            print("查询物品当前状态：", tallyRequestReceiveDept)

            if tallyRequestReceiveDept == '理货暂存库':
                print('验货结束')
                # 调用crm支付接口，自动支付有点慢，后续改进，目前先让订单自动支付

            else:
                self.scanAndBind()
                R.receiveProduct()
                self.InspectionProduct()
        else:
            print("理货查询物品报错")


if __name__ == '__main__':
    I = InspectionOperation()
    I.InspectionProduct()
    if step_wuliu == '5':
        os._exit(0)
    I.tally()
